import React from 'react'
import {
  BaseListPage,
  IBaseListPageState,
  IBaseListPageProps,
  columnRenders,
  UdDateRangePicker,
  http,
  UdTable,
  UdModal,
} from '@/lib'
import { Select, Table, Spin, Carousel, message, Modal, Badge, Tooltip } from 'antd'
import apis from '@/apis/AboutQuota'
import dayjs from 'dayjs'
import udMainStore from '@/store/UdMain'
import './style.scss'
import { WithToolbar } from '@/components/PhotoView'
const deleteBtnAuthAll = 'quota_employee_manager_delCheckStocksXGB'
const deleteBtnAuth = 'quota_employee_manager_delCheckStockDetailsXGB'

const confirm = Modal.confirm
const { Option } = Select
export default class ManualInventoryRecordList extends BaseListPage<
  ManualInventoryRecordListProps,
  ManualInventoryRecordListState
> {
  public hideArr: any = []

  protected useConditionsField = true
  constructor(props) {
    super(props)
    this.state = {
      title: '销售部手工盘点库存记录',
      selectData: [],
      loading: true,
      rowKey: 'id',
      queryApi: params => {
        this.GetDealerInfo()
        return http.post(apis.querySaleDealerCheck, params)
      },
      brandList: [],
      method: 'POST',
      conditions: [
        {
          id: 'brandCode',
          label: '销售组织',
          render: () => (
            <Select>
              {this.state.brandList.length > 0 &&
                this.state.brandList.map(({ value, title }) => {
                  return (
                    <Option key={value} value={value}>
                      {title}
                    </Option>
                  )
                })}
            </Select>
          ),
        },
        {
          id: ['inventoryBegineTime', 'inventoryEndTime'],
          label: '盘点时间',
          render: <UdDateRangePicker valueFormat={['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59']} />,
        },
        { id: 'dealerName', label: '客户名称' },
        { id: 'createName', label: '盘点业务人员' },
        {
          id: 'dealerType',
          label: '客户类型',
          render: () => (
            <Select placeholder="请选择状态">
              <Option value="DEALER">经销商</Option>
              <Option value="DISTRIBUTOR">分销商</Option>
            </Select>
          ),
        },
        {
          id: 'approvalStatus',
          label: '审批状态',
          render: () => (
            <Select placeholder="请选择状态">
              <Option value="AUDITING">审批中</Option>
              <Option value="AUDITSUCC">审批通过</Option>
              <Option value="AUDITFAIL">审批不通过</Option>
            </Select>
          ),
        },
      ],
      columns: [
        { title: '盘点周期', key: 'description', dataIndex: 'description', width: 160 },
        ['客户编码', 'dealerCode'],
        {
          title: '客户类型',
          key: 'dealerType',
          dataIndex: 'dealerType',
          render: recode => <span>{recode == 'DISTRIBUTOR' ? '分销商' : recode == 'DEALER' ? '经销商' : ''}</span>,
        },
        ['客户名称', 'dealerName'],
        ['销售组织', 'brandNameShort'],
        ['所属管理区域', 'belongAreaName'],
        ['盘点业务人员', 'createName'],
        {
          title: '库存盘点附件',
          width: 100,
          dataIndex: 'stockCertificate',
          render: (text, row) => {
            const urls = row.stockCertificate ? row.stockCertificate.split(',') : []
            if (row.stockCertificate) return <WithToolbar imagesList={urls} />
          },
          // render: (text, row) => text && <a onClick={() => this.openModalViewFile(row)} >盘点表凭证</a>
        },
        {
          title: '审批状态',
          width: 120,
          dataIndex: 'approvalStatus',
          render: (text, row) => {
            switch (text) {
              // 审批中
              case 'AUDITING':
                return <Badge color="orange" text={<span style={{ fontSize: '12px' }}>审批中</span>} />
              // 审批成功
              case 'AUDITSUCC':
                return <Badge color="green" text={<span style={{ fontSize: '12px' }}>审批通过</span>} />
              // 审批失败
              case 'AUDITFAIL':
                return <Badge color="red" text={<span style={{ fontSize: '12px' }}>审批不通过</span>} />
              default:
                return <span>--</span>
            }
          },
        },
        {
          title: '操作',
          width: 100,
          render: columnRenders.operate([
            {
              title: '删除',
              auth: deleteBtnAuthAll,
              action: (text: any, record: any) => {
                confirm({
                  title: '确定要删除该盘点单吗？',
                  onOk: () => {
                    return this.handleRemoveRecord(record)
                  },
                })
              },
            },
          ]),
        },
      ],
      tableProps: {
        scroll: { x: true },
        expandedRowRender: this.expandedRowRender,
        onExpand: this.onExpand,
      },
    }
  }
  // 获取销售组织列表
  GetDealerInfo() {
    http
      .get(apis.GetDealerInfo)
      .then(res => {
        // 设置销售选择销售组织的数组
        let tmpData: [] = res.data
        let hideArr = []
        tmpData.forEach((item: { brandCode: string; brandName: string }, index) => {
          hideArr.push({ value: item.brandCode, title: item.brandName })
        })
        // 修改
        this.hideArr = hideArr
        this.setState({ brandList: hideArr })
      })
      .catch(err => {
        throw err
      })
  }
  private onExpand = (expanded, record) => {
    if (!expanded) return null
    localStorage.setItem('historyRecord', record.id)
    http.get(apis.CheckStockListDetail, { params: { id: record.id } }).then(resp => {
      let value = [...this.state.selectData]
      value[record.id] = resp.data
      this.setState({
        loading: false,
        selectData: value,
      })
    })
  }
  private expandedRowRender = (recode, index) => {
    const columns = [
      { title: '序号', dataIndex: 'id', key: 'id', width: 50, render: (text, reoled, index) => index + 1 },
      { title: '物料编码', dataIndex: 'prodBarcode', key: 'prodBarcode', width: 100 },
      { title: '物料描述', key: 'matName', dataIndex: 'matName', width: 150 },
      { title: '期初库存(含未到货)/件', dataIndex: 'beginningRealStock', key: 'beginningRealStock', width: 146 },
      { title: '期间开单/件', dataIndex: 'nowAog', key: 'nowAog', width: 140 },
      { title: '调入调出', dataIndex: 'allocateNumber', key: 'allocateNumber', width: 100 },
      { title: '当前实物库存/件', dataIndex: 'nowRealStock', key: 'nowRealStock', width: 140 },
      { title: '当前未到货/件', dataIndex: 'onOrder', key: 'onOrder', width: 130 },
      { title: '期间动销数/件', dataIndex: 'nowMove', key: 'nowMove', width: 100 },
      { title: '下月订单计划/件', dataIndex: 'nextMonthOrderNum', key: 'nextMonthOrderNum', width: 130 },
      {
        title: '动销说明',
        dataIndex: 'nowMoveDes',
        key: 'nowMoveDes',
        width: 130,
        render: (text, record) => {
          return (
            <Tooltip title={record.nowMoveDes}>
              <div style={{ width: '130px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                {record.nowMoveDes}
              </div>
            </Tooltip>
          )
        },
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        width: 130,
        render: (text, record) => {
          return (
            <Tooltip title={record.remark}>
              <div style={{ width: '130px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                {record.remark}
              </div>
            </Tooltip>
          )
        },
      },
      {
        title: '操作',
        width: 100,
        render: columnRenders.operate([
          {
            title: '删除',
            auth: deleteBtnAuth,
            action: (text: any, record: any) => {
              confirm({
                title: '确定要删除该物料吗？',
                onOk: () => {
                  return this.handleRemove(record)
                },
              })
            },
          },
        ]),
      },
    ]

    return (
      <Spin spinning={this.state.loading}>
        <UdTable columns={columns} dataSource={this.state.selectData[recode.id]} pagination={false} rowKey="id" />
      </Spin>
    )
  }

  private openModalViewFile = row => {
    const urls = row.stockCertificate ? row.stockCertificate.split(',') : []
    UdModal.open({
      content: (
        <Carousel className="certificate-carousel" autoplay>
          {urls.map(url => (
            <div>
              <img src={url} alt="凭证" />
            </div>
          ))}
        </Carousel>
      ),
      footer: null,
    })
  }

  private handleRemove = row => {
    http
      .post(apis.DeleteStorage, [row.id])
      .then(res => {
        message.success('删除成功')
        let data = localStorage.getItem('historyRecord')
        http.get(apis.CheckStockListDetail, { params: { id: data } }).then(resp => {
          let value = [...this.state.selectData]
          value[data] = resp.data
          this.setState({
            loading: false,
            selectData: value,
          })
        })
        this.query()
        this.forceUpdate()
      })
      .catch(() => {})
  }

  private handleRemoveRecord = row => {
    http
      .post(apis.DeleteStorageRecord, [row.id])
      .then(res => {
        message.success('删除成功')
        this.query()
      })
      .catch(() => {})
  }
}

interface ManualInventoryRecordListState extends IBaseListPageState {
  loading: boolean
  selectData: any
  brandList?: any[]
}

interface ManualInventoryRecordListProps extends IBaseListPageProps {}
